package com.example.demo.controller;


import com.example.demo.constant.CommonConstant;
import com.example.demo.entity.User;
import com.example.demo.entity.dto.ResultBean;
import com.example.demo.entity.vo.PasswordVo;
import com.example.demo.entity.vo.UserVo;
import com.example.demo.service.UserService;
import com.example.demo.util.MailPre;
import com.example.demo.util.Permission;
import com.example.demo.util.RedisUtil;
import com.example.demo.util.Role;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cy
 * @since 2020-08-01
 * @version v1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;

    /**
    * 查询分页数据
    */
    @RequestMapping(method = RequestMethod.GET)
    public ResultBean<?> listByPage(@RequestParam(name = "page", defaultValue = "1") int page,
                                    @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                    @RequestParam(name = "factor", defaultValue = "") String factor,
                                    @RequestParam(name = "teamState", defaultValue = "") Integer teamState,
                                    @RequestParam(name = "firmState", defaultValue = "") Integer firmState) {
        return new ResultBean<>(userService.listUsersByPage(page, pageSize,factor,teamState,firmState));
    }

    /**
     * 权限管理查询分页用户数据
     */
    @RequestMapping(method = RequestMethod.GET,value = "/adminList")
    @RequiresPermissions(Permission.MANAGE_PERMISSION)
    public ResultBean<?> adminListByPage(@RequestParam(name = "page", defaultValue = "1") int page,
                                    @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                    @RequestParam(name = "factor", defaultValue = "") String factor,
                                    @RequestParam(name = "teamState", defaultValue = "") Integer teamState,
                                    @RequestParam(name = "firmState", defaultValue = "") Integer firmState) {
        return new ResultBean<>(userService.adminListUsersByPage(page, pageSize,factor,teamState,firmState));
    }


    /**
    * 根据id查询
    */
    @RequestMapping(method = RequestMethod.GET, value = "/normal/{id}")
    public ResultBean<?> getById(@PathVariable("id") Integer id) {
        return new ResultBean<>(userService.getUserById(id));
    }

    /**
    * 新增
    */
    @RequestMapping(value = "/normal",method = RequestMethod.POST)
    public ResultBean<?> insert(@RequestBody UserVo user) {
        return new ResultBean<>(userService.insertUser(user));
    }

    /**
     * 新增账户
     */
    @RequestMapping(value = "/normal/normalInsert",method = RequestMethod.POST)
    public ResultBean<?> normalInsert(@RequestBody User user) {
        return new ResultBean<>(userService.normalInsertUser(user));
    }

    /**
    * 删除
    */
    @RequiresRoles(Role.ADMIN)
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
    public ResultBean<?> deleteById(@PathVariable("id") Integer id) {
        return new ResultBean<>(userService.deleteUserById(id));
    }

    /**
    * 修改
    */
    @RequestMapping(method = RequestMethod.PUT)
    public ResultBean<?> updateById(@RequestBody User user) {
        User userPo = (User) SecurityUtils.getSubject().getPrincipal();
        user.setUserId(userPo.getUserId());
        return new ResultBean<>(userService.updateUser(user));
    }

    @RequestMapping(method = RequestMethod.POST, value = "/login")
    public ResultBean<com.alibaba.fastjson.JSONObject> Login(@RequestBody User user){
        return new ResultBean<>(userService.login(user));
    }

    @RequestMapping(method = RequestMethod.GET, value = "/normal/sendCode")
    public ResultBean<String> sendMail(@RequestParam("mail") String mail, @RequestParam(value = "tag",defaultValue = "0")Integer tag){
        String pre ;
        if (tag==0){
            //注册
            pre = MailPre.REGISTER;
        }else if (tag==1){
            //重置邮箱
            pre = MailPre.RESET_MAIL;
        }else {
            //忘记密码
            pre = MailPre.RESET_PWD;
        }
        if (userService.sendMail(pre,mail)){
            return new ResultBean<>("发送邮件成功");
        }
        return new ResultBean<>("发送邮件失败，请检查邮箱是否正确");
    }

    @RequestMapping(method = RequestMethod.GET, value = "/normal/checkAccount")
    public ResultBean checkAccount(@RequestParam("account") String account){
        if (userService.getUserByAccount(account)!=null){
            return new ResultBean("此账户已注册",ResultBean.SUCCESS_CODE,0);
        }
        return new ResultBean("此账户未注册，可以进行注册",ResultBean.SUCCESS_CODE,1);
    }

    @RequestMapping(method = RequestMethod.PUT, value = "/resetPwd")
    public ResultBean<Integer> resetPwd(@RequestBody PasswordVo passwordVo, HttpServletRequest request){
        User user= (User) SecurityUtils.getSubject().getPrincipal();
        int result = userService.resetPwd(user,passwordVo.getOldPwd(),passwordVo.getNewPwd());
        String token = request.getHeader("token");
        redisUtil.del(CommonConstant.PREFIX_USER_TOKEN+token);
        return new ResultBean<>(result);
    }

    @RequestMapping(method = RequestMethod.PUT, value = "/resetMail")
    public ResultBean<Integer> resetMail(@RequestBody UserVo user){
        User userPo = (User) SecurityUtils.getSubject().getPrincipal();
        user.setUserId(userPo.getUserId());
        return new ResultBean<>(userService.resetMail(user));
    }

    @RequestMapping(method = RequestMethod.PUT, value = "/normal/forgetPwd")
    public ResultBean<Integer> forgetPwd(@RequestBody UserVo userPo){
        return new ResultBean<>(userService.forgetPwd(userPo));
    }

    /**
     * 用户团队认证
     * @param userPo
     * @return
     */
    @RequestMapping(method = RequestMethod.PUT, value = "/teamAuthenticate")
    public ResultBean<?> teamAuthenticate(@RequestBody User userPo){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        userPo.setUserId(user.getUserId());
        userPo.setTeamState(User.TEAM_REQUEST);
        return new ResultBean<>(userService.teamAuthenticate(userPo));
    }


    /**
     * 用户企业认证
     * @param userPo
     * @return
     */
    @RequestMapping(method = RequestMethod.PUT, value = "/firmAuthenticate")
    public ResultBean<?> firmAuthenticate(@RequestBody User userPo){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        userPo.setUserId(user.getUserId());
        userPo.setFirmState(User.FIRM_REQUEST);
        return new ResultBean<>(userService.firmAuthenticate(userPo));
    }

    /**
     * 团队认证审核
     * @param id
     * @param flag
     * @return
     */
    @RequiresRoles(Role.ADMIN)
    @RequestMapping(method = RequestMethod.PUT,value = "checkTeam/{id}/{flag}")
    public ResultBean<?> checkTeam(@PathVariable("id") Integer id,@PathVariable("flag")Boolean flag){
        return new ResultBean<>(userService.checkTeam(id,flag));
    }


    /**
     * 企业认证审核
     * @param id
     * @param flag
     * @return
     */
    @RequiresRoles(Role.ADMIN)
    @RequestMapping(method = RequestMethod.PUT,value = "checkFirm/{id}/{flag}")
    public ResultBean<?> checkFirm(@PathVariable("id") Integer id,@PathVariable("flag")Boolean flag){
        return new ResultBean<>(userService.checkFirm(id,flag));
    }

    @RequestMapping(method = RequestMethod.GET,value = "/loginOut")
    public ResultBean<?> loginOut(HttpServletRequest request){
        String token = request.getHeader("token");
        return new ResultBean<>(userService.loginOut(token));
    }



}
